#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :app.py
# @Time      :2025/2/13 17:50
# @Author    :kk
from datetime import datetime

#从 flask 模块导入 Flask 类
from flask import Flask, request, render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text

# 穿件一个app 对象
app = Flask(__name__) # __name__ 表示当前模块名

#
class User:
    def __init__(self,name,age):
        self.name = name
        self.age = age


HOSTNAME = "10.15.82.74"
PORT = 3306
USERNAME = "root"
PASSWORD = "123456"
DATABASE = "flask_demo"
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4".format(
    USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE
)

db = SQLAlchemy(app)
with app.app_context():
    with db.engine.connect() as conn:
        rs = conn.execute(text("select 1"))
        print(rs.fetchone()) #(1,)





# 创建一个路由和视图函数的映射
# /home/user/xx
@app.route("/")
def index():
    #return "hello world...."
    return render_template("index.html")

@app.route("/profile")
def profile():
    return "我是个人中心"

@app.route("/blog/list")
def blog_list():
    return "我是博客列表"

# 带参数的url
# string、int、float、path、uuid、any(枚举)
# 枚举: <any(python,flask,django):category>
# 将参数固定到path中
@app.route("/blog/<int:blog_id>")
def blog_detail(blog_id):
    #return "您访问的博客是:%s" % blog_id
    user = User("kk",18)
    dict_obj = {
        "dict_name" : "字典值"
    }
    return render_template("blog_detail.html",blog_id=blog_id,user = user,dict_obj = dict_obj)


# 过滤器
def datetime_formate(value,format="%Y-%m-%d %H:%M:%S"):
    return value.strftime(format)
# 自定义过滤器
app.add_template_filter(datetime_formate,"dformat")
@app.route("/filter")
def demo_filter():
    user = User("老大人",33)
    mytime = datetime.now()
    return render_template("filter.html",user = user,mytime = mytime)

# 控制语句
@app.route("/control")
def demo_control():
    user = User("老王",33)
    books = [{
        "name": "西游记",
        "auth": "吴承恩"
    },{
        "name": "三国演义",
        "auth": "罗贯中"
    },{
        "name": "水浒传",
        "auth": "施耐庵"
    },{
        "name": "红楼梦",
        "auth": "曹雪芹"
    }]
    return render_template("control.html",user = user,books = books)

@app.route("/child1")
def demo_child():
    return render_template("child1.html")

@app.route("/child2")
def demo_child2():
    return render_template("child2.html")

@app.route("/static")
def demo_static():
    return render_template("static.html")

# 查询字符串的方式传参
# /book/list
# /book/list?page=2
@app.route("/book/list")
def book_list():
    # argument: 参数
    # request.args: 字典类型
    page = request.args.get("page",default=1,type=int)
    return f"您获取的是第{page}的图书列表!"

# 1.debug模式:

# 2.修改host:
# app.run(host="0.0.0.0")
# 3.修改端口:
# app.run(port=8080)


if __name__ == '__main__':
    app.run(debug=True)

